package cn.livingCloud.controller.user.validator;

import cn.livingCloud.dto.UserAccountFormDto;
import cn.livingCloud.service.UserAccountService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.ValidationUtils;
import org.springframework.validation.Validator;

/**
 * Created by sujiantang on 2015/12/8.
 */
@Component
public class UserAccountFormDtoValidator implements Validator {
    @Qualifier("userAccountServiceImpl")
    @Autowired
    private UserAccountService userAccountService;

    @Override
    public boolean supports(Class<?> aClass) {
        return UserAccountFormDto.class.equals(aClass);
    }

    @Override
    public void validate(Object target, Errors errors) {
        UserAccountFormDto formDto = (UserAccountFormDto) target;
        ValidationUtils.rejectIfEmptyOrWhitespace(errors, "userId", null, "请选择用户");
        validateUsername(formDto, errors);
        validatePassword(formDto, errors);
    }

    private void validatePassword(UserAccountFormDto formDto, Errors errors) {
        //新建
        if (StringUtils.isEmpty(formDto.getUuid())) {
            if (StringUtils.isEmpty(formDto.getPassword())) {
                errors.rejectValue("password", null, "密码不能为空");
            }
        } else {
            //更新账号信息
            if (!StringUtils.isEmpty(formDto.getPassword())) {
                errors.rejectValue("password", null, "不能更改密码");
            }
        }
    }

    private void validateUsername(UserAccountFormDto formDto, Errors errors) {
        String username = formDto.getUsername().trim();
        if (StringUtils.isEmpty(username)) {
            errors.rejectValue("username", null, "账号不能为空");
        }
        if (StringUtils.isEmpty(formDto.getUuid())) {
            if (userAccountService.check(username)) {
                errors.rejectValue("username", null, "账号重复");
            }
        }

    }
}
